<template>
  <div class="page">
    <div class="mb-3">
      <el-button @click="handleAddNewQuestion" type="success">新增题目</el-button>
    </div>
    <el-table
      :data="questionList"
      height="70vh"
      border
      v-loading="loading"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="title"
        label="题目"
        width="280">
      </el-table-column>
      <el-table-column
        prop="sort"
        width="50"
        label="排序">
      </el-table-column>
      <el-table-column
        prop="add_time"
        width="180"
        label="添加时间">
        <template slot-scope="scope">
          <el-tag v-text="new Date(scope.row.add_time * 1000).toLocaleString()"></el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        width="100"
        label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'"
                  v-text="scope.row.status === 1 ? '显示' : '隐藏'"></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="答案">
        <template slot-scope="scope">
          <el-tag class="answer" v-for="answer in scope.row.qa_answer" :key="answer.id" v-text="answer.title"></el-tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        width="200"
        label="操作">
        <template slot-scope="scope">
          <el-button plain type="warning" @click="handleEdit(scope.row)" size="small">编辑</el-button>
          <el-button plain type="danger" @click="handleDelete(scope.row)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="meta.limit"
      :current-page="meta.page"
      @current-change="handleCurrentPageChange"
      hide-on-single-page
      :total="meta.total">
    </el-pagination>

    <el-dialog
      :visible.sync="visibles.visibleEdit"
      @close="handleDialogClose('dataForm')"
      :before-close="cancel"
      width="50%">
      <el-form ref="dataForm" label-width="80px" :rules="rules" :model="dataForm">
        <el-form-item v-show="operating === 'alter'" label="id" prop="id">
          <el-input readonly v-model="dataForm.id"></el-input>
        </el-form-item>
        <el-form-item label="题目" prop="title">
          <el-input clearable v-model="dataForm.title" placeholder="请填入题目"></el-input>
        </el-form-item>
        <el-form-item label='排序' prop="sort">
          <el-input-number clearable v-model="dataForm.sort" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="答案">
          <div class="answer_item" v-for="(answerItem, index) in answers" :key='JSON.stringify(answerItem) + index'>
            <div class="answer_title">
              <el-input v-model="answerItem.title" clearable placeholder="请输入选项"></el-input>
            </div>
            <div class="answer_sort">
              <el-input-number :min="0" v-model="answerItem.sort"></el-input-number>
            </div>
          </div>
          <el-button @click="handleAddAnswer()">增加一个</el-button>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button type="info" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getQuestionList,
  deleteQuestion,
  toAddOrAlterQues,
  getQuestionDetail
} from "@/api/questionBank/questionBank";

export default {
  name: "questionList",
  data() {
    return {
      questionList: [],
      loading: true,
      visibles: {     // 所有的模态框开关
        visibleEdit: false,
      },
      meta: {},   // 元信息 分页信息
      // currentPage: 1,
      operating: 'add',    // 当前操作 add 添加题目  alter 修改题目
      rules: {
        title: [
          { required: true, message: '请输入题目名称！', trigger: 'blur' },
        ]
      },
      dataForm: {
        id: '',
        title: '',
        sort: 0,
      },
      answers: [
        {title: '', sort: ''},
        {title: '', sort: ''},
        {title: '', sort: ''},
        {title: '', sort: ''},
      ],
    }
  },
  mounted() {
    this.refreshData()
  },
  methods: {
    async refreshData(page) {
      let data
      if (page) {
        const res = await getQuestionList(page)
        data = res['data']
      } else {
        const res = await getQuestionList()
        data = res['data']
      }
      this.meta = data.meta
      this.questionList = data.list
      this.loading = false
    },
    async handleDelete(rowData) {
      const {code} = await deleteQuestion(rowData.id)
      if (code === 200) {
        this.$message.success('删除成功！')
        await this.refreshData()
      } else {
        this.$message.error('删除失败！')
      }
    },
    handleEdit(rowData) {
      this.operating = 'alter'
      this.visibles.visibleEdit = true
      this.answers.forEach((item, index) => {
        item.title = rowData['qa_answer'][index].title
        item.sort = rowData['qa_answer'][index].sort
      })
      // this.answers = rowData['qa_answer']
      this.dataForm = rowData
    },
    cancel() {
      this.visibles.visibleEdit = false
      this.dataForm =  {
        id: '',
        title: '',
        sort: 0,
      }
      this.answers = [
        {title: '', sort: ''},
        {title: '', sort: ''},
        {title: '', sort: ''},
        {title: '', sort: ''},
      ]
    },
    handleAddAnswer() {
      this.$set(this.answers, this.answers.length, {title: '', sort: ''})
    },
    submitForm() {
      this.$refs['dataForm'].validate(async valid => {
        if (!valid) return
        if (this.operating === 'add') {
          if (!this.dataForm.title.trim()) {
            this.$message.error("请输入标题")
            return
          }
          const {code} = await toAddOrAlterQues({
            title: this.dataForm.title,
            sort: this.dataForm.sort,
            answers: JSON.stringify(this.answers)
          })
          if (code === 200) {
            this.$message.success('添加成功！')
            this.loading = true
            this.visibles.visibleEdit = false
            await this.refreshData()
            this.loading = false
          }
        } else if (this.operating === 'alter') {
          const {code} = await toAddOrAlterQues({...this.dataForm, answers: JSON.stringify(this.answers)})
          if (code === 200) {
            this.$message.success('修改成功！')
            this.loading = true
            this.visibles.visibleEdit = false
            await this.refreshData()
            this.loading = false
          }
        }
      })
    },
    handleAddNewQuestion() {
      this.operating = 'add'
      this.visibles.visibleEdit = true
    },
    handleCurrentPageChange(page) {
      this.refreshData(page)
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
        if (this.$refs[formName]) {
            this.$refs[formName].clearValidate(); // 清除整个表单的校验
        }
    },
  }
}
</script>

<style lang="scss" scoped>
@import "style";
</style>
